package com.fll.fangyiuser.controller;

import com.aliyun.oss.ServiceException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fll.fangyicommon.entity.ResultOk;
import com.fll.fangyicommon.entity.user.Friend;
import com.fll.fangyicommon.entity.user.Oss;
import com.fll.fangyicommon.entity.user.User;
import com.fll.fangyicommon.utils.OssUtil;
import com.fll.fangyiuser.service.FriendService;
import com.fll.fangyiuser.service.OssService;
import com.fll.fangyiuser.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author fll
 * create 2023/2/25
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class FriendController {

    @Autowired
    private UserService userService;

    @Autowired
    private FriendService friendService;

    //添加好友
    @GetMapping("/addFriend")
    public ResultOk addFriend(@Param("friendId") Integer friendId, @RequestHeader String userInfo) {

        ResultOk ok = new ResultOk();
        if (friendId == null) {
            ok.setCode(400);
            ok.setMsg("用户id不能为空！");
            return ok;
        }
        if (userService.getUserInfoByUserId(friendId) == null) {
            ok.setCode(400);
            ok.setMsg("用户不存在!");
            return ok;
        }
        User user = null;
        ;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
            if (friendId.equals(user.getUserId())) {
                ok.setCode(400);
                ok.setMsg("不能添加自己为好友！");
                return ok;
            }
            //通过两个用户id验证是否为朋友
            Friend isFriend = friendService.verifyFriend(user.getUserId(), friendId);
            if (isFriend != null) {
                if (isFriend.getState() == 1) {
                    ok.setCode(400);
                    ok.setMsg("你们已经是好友啦！");
                    return ok;
                }//按理说应该走这里的if，但是你看效果.没走这里
                if (isFriend.getState() == 0) {
                    ok.setCode(400);
                    ok.setMsg("你已发送过请求了！");
                    return ok;
                }
            }
            /**
             * 此处之前踩过一次坑，添加好友时只在friend关系表新增一条记录，而同意的时候除了把已添加的一条state设置为1，还要新增另外一条记录也把state设置为1
             */
            //否则添加进friend表（代表发送了好友添加请求）
            Friend friend = new Friend();
            //user_id为本用户，friend_id为对方
            friend.setUserId(user.getUserId());
            friend.setFriendId(friendId);
            friend.setState(0);
            Integer num1 = friendService.insert(friend);

            if (num1 != null || num1 != 0) {
                ok.setCode(200);
                ok.setMsg("发送请求成功!");
                return ok;
            }

        } catch (Exception e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("后端异常！");
            return ok;
        }
        ok.setCode(400);
        ok.setMsg("未知错误！");
        return ok;
    }

    //根据state查询好友列表
    @GetMapping("/getFriend")
    public ResultOk getFriend(@RequestParam("state") Integer state, @RequestHeader String userInfo) {

        ResultOk<List> ok = new ResultOk();

        User user = null;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
            //由于添加好友在friend表中加入的是两条记录，user_id就为当前用户id，friend_id为好友id
            List<Friend> friendList = friendService.getFriendByUserId(user.getUserId(), state);
            if (state == 0 && friendList == null) {
                ok.setCode(400);
                ok.setMsg("暂无好友申请!");
                return ok;
            }
            if (state == 1 && friendList == null) {
                ok.setCode(400);
                ok.setMsg("暂无好友!");
                return ok;
            }
            ok.setCode(200);
            ok.setMsg("查询成功！");
            ok.setData(friendList);
            return ok;
        } catch (Exception e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("后端异常！");
        }
        return ok;
    }

    //同意好友申请
    @PostMapping("/agreeFriend")
    @Transactional(rollbackFor = Exception.class)
    public ResultOk agreeFriend(@RequestBody Map<String, Object> params, @RequestHeader String userInfo) throws JsonProcessingException {

        Integer friendId = (Integer) params.get("friendId");
        ResultOk<User> ok = new ResultOk<>();
        User user = new ObjectMapper().readValue(userInfo, User.class);
        /**
         * 此处之前踩过一次坑，添加好友成功后应该在friend表新增两条记录，而不是一条，这样也符合qq的逻辑，存在单向好友
         * 即之前未同意的那条记录state设置为1，重新把friend_id和user_id对换再加入一条
         * 如果只新增一条记录，根据用户id获取用户好友列表也会复杂化（即friend表中user_id和friend_id都可能是好友的id），添加两条记录完美避开
         * 同时要保证添加两条记录要么同时成功要么同时失败
         */
        Integer num1 = friendService.agreeFriend(user.getUserId(), friendId);
        if (num1 == 0) {
//            throw new GlobleException("dsd");
            throw new IllegalArgumentException("数据库更新结果为0");
        }

        Friend friend = new Friend();
        friend.setUserId(user.getUserId());
        friend.setFriendId(friendId);
        friend.setState(1);
        Integer num2 = friendService.insert(friend);
        if (num1 != 0 && num2 != 0) {
            ok.setCode(200);
            ok.setMsg("同意成功！");
            return ok;
        }

        ok.setCode(400);
        ok.setMsg("未知错误！");
        return ok;
    }

    //删除好友
    @PostMapping("/deleteFriend")
    @Transactional(rollbackFor = Exception.class)
    public ResultOk deleteFriend(@RequestBody Map<String, Object> params, @RequestHeader String userInfo) throws JsonProcessingException {

        ResultOk<User> ok = new ResultOk<>();
        Integer friendId = (Integer) params.get("friendId");
        if (friendId == null){
            ok.setCode(400);
            ok.setMsg("好友id不能为空");
            return ok;
        }

        User user = new ObjectMapper().readValue(userInfo, User.class);
        Integer num1 = friendService.deleteFriend(user.getUserId(), friendId);
        Integer num2 = friendService.deleteFriend(friendId, user.getUserId());
        if (num1 == 0 || num2 == 0){
            throw new ServiceException("删除好友需把friend表里两条记录删除！");
        }
        if (num1 != 0 && num2 != 0){
            ok.setCode(200);
            ok.setMsg("删除成功！");
            return ok;
        }
        ok.setCode(400);
        ok.setMsg("未知错误！");
        return ok;
    }

    //查询共同好友
    @GetMapping("/getSameFriend")
    public ResultOk getSameFriend(@RequestParam("friendId") Integer friendId, @RequestHeader String userInfo) {
        User user = null;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return friendService.getSameFriend(user.getUserId(), friendId);
    }


    /**
     * openFeign远程调用，查询出好友的user_id
     * @param userId
     * @return
     */
    @GetMapping("/getFriendByRpc")
    public String getFriendByRpc(@RequestParam Integer userId) {
       return friendService.getFriendByRpc(userId);
    }

}
